﻿<%@ WebHandler Language="C#" Class="ShowListNotLitigation" %>

using System;
using System.Web;
using System.Text;
using System.Data;
using Chenxin.Lib.Utility;
using Chenxin.Lib.Business;
using Chenxin.Lib.Business.BLL;

public class ShowListNotLitigation : AjaxHandlerBase
{
    /// <summary>
    /// 基本权限项
    /// </summary>
    public ShowListNotLitigation()
    {
        //非诉申请
        htTypePermit.Add("nolitigation", Constants.Permit_NoLitigation);
        //非诉更新
        htTypePermit.Add("upnolitigation", Constants.Permit_UpdateNoLitigation);
        //非诉附件列表
        htTypePermit.Add("showattachnotlitigation", Constants.Permit_ShowAttachNotLitigation);
        //非诉上传附件
        htTypePermit.Add("notlituploadattach", Constants.Permit_NotLitUpLoadAttach);
        //导出
        htTypePermit.Add("export", Constants.Permit_NotLitigation_Export);  
    }

    //可上传附件类型
    public static string[] FileExt = new string[] { ".xls", 
                                                    ".doc", 
                                                    ".pdf", 
                                                    ".rar", 
                                                    ".zip", 
                                                    ".jpg", 
                                                    ".xlsx", 
                                                    ".docx" };

    override public void RequestProcess(HttpContext context)
    {
        string strOp = context.Request["op"];
        string strResponse = "";
        switch (strOp.ToLower())
        {
            //获取实体
            case "getmodel":
                strResponse = GetModel(context);
                break;
            //获取实体
            case "getdepart":
                strResponse = GetDepart(context);
                break;
            //查询
            case "search":
                strResponse = Search(context);
                break;
            //非诉申请
            case "nolitigation":
                strResponse = Apply(context);
                break;
            //非诉更新
            case "upnolitigation":
                strResponse = Update(context);
                break;
            //上传附件
            case "fileupload":
                strResponse = FileUpload(context);
                break;
            //附件列表
            case "showattachnotlitigation":
                strResponse = ShowList(context);
                break;
            default:
                break;
        }
        context.Response.Write(strResponse);
    }

    /// <summary>
    /// 获取实体
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string GetModel(HttpContext context)
    {
        try
        {
            Chenxin.Lib.Business.Entity.t_Business_NotLitigationInfo model = null;

            model = Chenxin.Lib.Business.DAL.t_Business_NotLitigationInfo.GetModel(new Guid(context.Request["modelid"]));

            if (model != null)
            {
                return retExecResult(Constants.ExecResult.Succ, "", model);
            }
            else
            {
                return retExecResult(Constants.ExecResult.Error, "数据不存在，获取信息失败！", "");
            }
        }
        catch (Exception ex)
        {
            return retExecResult(Constants.ExecResult.Error, ex.Message, "");
        }
    }

    /// <summary>
    /// 获取实体
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string GetDepart(HttpContext context)
    {
        try
        {
            Chenxin.Lib.Business.Entity.t_Business_NotLitigationInfo model = new Chenxin.Lib.Business.Entity.t_Business_NotLitigationInfo();
            model.AppDepartId = CurrentUserInfo.DepartId;
            model.AppDepart = CurrentUserInfo.DepartName;
            return retExecResult(Constants.ExecResult.Succ, "", model);
        }
        catch (Exception ex)
        {
            return retExecResult(Constants.ExecResult.Error, ex.Message, "");
        }
    }
    
    //*******************************************
    //功能概要       ：获得非诉一览
    //参数説明       ：context 请求的上下文
    //返回值説明     ：无
    //功能詳細       ：获得非诉一览
    //作成者         ：zou.xiaochun
    //作成日         ：2010-10-08
    //*******************************************
    private string Search(HttpContext context)
    {
        try
        {
            //页码
            int strPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;
            //页显示行数
            int strPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);
            //查询条件
            string sqlWhere = GenerateCondition(context);

            //查询分页信息
            Chenxin.Lib.Business.BLL.NotLitigationInfo bllNoLit = new Chenxin.Lib.Business.BLL.NotLitigationInfo();
            System.Data.DataSet ds = bllNoLit.GetModelListByCoditions(sqlWhere, strPageIndex, strPageSize);
            //总页数
            int count = (int)ds.Tables[1].Rows[0][0];

            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',{2}}}}}", Resources.Message.Global_Msg_SUCCESS, count, JsonHelp.Convert2Json(ds.Tables[0]));
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
        }
    }

    //*******************************************
    //功能概要       ：查询权限
    //参数説明       ：context 请求上下文
    //返回值説明     ：程序处理信息提示
    //功能詳細       ：生成查询条件语句
    //作成者         ：chen.yugong
    //作成日         ：2010-06-29
    //修改者         ：王玮
    //修改日         ：2010-07-13
    //*******************************************
    public string GenerateCondition(HttpContext context)
    {
        try
        {
            //获取页面查询条件
            Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
            Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid employee = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);

            string starttime = context.Request.QueryString["DateFr"];
            string endtime = context.Request.QueryString["DateTo"];
            string keyword = context.Request.QueryString["HouseAddress"];

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            //判断级联菜单
            if (employee != Guid.Empty)
                sb.AppendFormat(" and (AddPersonId = '{0}') ", employee);
            else if (departs != Guid.Empty)
                sb.AppendFormat(" and (AppDepartId = '{0}')", departs);
            else if (businessdistrict != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null) return string.Format("{{success:'0',msg:'{0}',data:''}}", Resources.Message.Global_Err_GetBusDis);

                sb.AppendFormat(" and (AppDepartId in (select departId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (company != Guid.Empty)
            {
                sb.AppendFormat(" and AppCompanyId = '{0}'", company);
            }
            else if (city != Guid.Empty)
            {
                sb.AppendFormat(" and AppCityId = '{0}'", city);
            }
            else
            {
                sb.AppendFormat(" and AppCompanyId = '{0}'", CurrentUserInfo.CompanyId);
            }
            
            //查询权限判断权限
            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_NotLitigationSearch_All))
            {
                sb1.Append(" (1=1) ");
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_NotLitigationSearch_City))
            {
                sb1.AppendFormat(" (AppCityId = '{0}')", CurrentUserInfo.CityId);
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_NotLitigationSearch_Company))
            {
                sb1.AppendFormat(" (AppCompanyId = '{0}')", CurrentUserInfo.CompanyId);
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_NotLitigationSearch_Depart))
            {
                sb1.Append(" (EXISTS(");
                sb1.AppendFormat("Select 1 from t_Business_EmpSetting M WHERE t_Business_NotLitigationInfo.AppDepartId=M.DepartId And M.Userid= '{0}' and SearchNotLitigation=1", CurrentUserInfo.UserId.ToString());
                sb1.Append(")) ");
            }
            else
            {
                sb1.AppendFormat(" (AddPersonId = '{0}')", CurrentUserInfo.UserId);
            }

            if (!String.IsNullOrEmpty(sb.ToString()))
                sb1.Append(sb.ToString());

            if (!String.IsNullOrEmpty(starttime))
            {
                sb1.Append(string.Format(" and convert(varchar(10),(convert(datetime,AcceptedDate,120)),120)  >= '{0}'", (starttime)));
            }
            if (!String.IsNullOrEmpty(endtime))
            {
                sb1.Append(string.Format(" and convert(varchar(10),(convert(datetime,AcceptedDate,120)),120)  <= '{0}'", (endtime)));
            }
            if (!String.IsNullOrEmpty(keyword))
            {
                sb1.AppendFormat(" And HouseAddress LIKE '%{0}%'", keyword);
            }
            return sb1.ToString();
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
        }
    }
    
    //*******************************************
    //功能概要       ：非诉申请
    //参数説明       ：context 请求的上下文
    //返回值説明     ：无
    //功能詳細       ：非诉申请
    //作成者         ：zou.xiaochun
    //作成日         ：2010-10-08
    //*******************************************
    private string Apply(HttpContext context)
    {
        //非诉申请信息
        string notlitigation = context.Request.Params["model"];

        //非诉信息业务类
        Chenxin.Lib.Business.BLL.NotLitigationInfo bllNotLitigation = new Chenxin.Lib.Business.BLL.NotLitigationInfo();

        //非诉信息
        Chenxin.Lib.Business.Entity.t_Business_NotLitigationInfo entNotLitigation =
            (Chenxin.Lib.Business.Entity.t_Business_NotLitigationInfo)JsonHelp.Convert2Entity(notlitigation,
                    typeof(Chenxin.Lib.Business.Entity.t_Business_NotLitigationInfo));

        entNotLitigation = CompleteNotLitigation(entNotLitigation, "非诉申请");
        //非诉信息录入
        bllNotLitigation.Add(entNotLitigation);
        Chenxin.Lib.Business.DAL.t_Contract_BaseInfo.ChangeStatus(entNotLitigation.ContractCode, 10);

        string text = string.Empty;
        text = CurrentUserInfo.UserName + "：非诉申请。成交编号：" + entNotLitigation.ContractCode;
        AddLog(text, BusinessType.BusinessTypeComboList()["OprType_ApplyNotLitigation"].ToString());
        
        return retExecResult(Constants.ExecResult.Succ, Resources.Message.Msg_NotLitigation_Succ, "");
    }

    //*******************************************
    //功能概要       ：非诉更新
    //参数説明       ：context 请求的上下文
    //返回值説明     ：无
    //功能詳細       ：非诉申请
    //作成者         ：zou.xiaochun
    //作成日         ：2010-10-08
    //*******************************************
    private string Update(HttpContext context)
    {
        //非诉申请信息
        string notlitigation = context.Request.Params["model"];

        //非诉信息业务类
        Chenxin.Lib.Business.BLL.NotLitigationInfo bllNotLitigation = new Chenxin.Lib.Business.BLL.NotLitigationInfo();

        //非诉信息
        Chenxin.Lib.Business.Entity.t_Business_NotLitigationInfo entNotLitigation =
            (Chenxin.Lib.Business.Entity.t_Business_NotLitigationInfo)JsonHelp.Convert2Entity(notlitigation,
                    typeof(Chenxin.Lib.Business.Entity.t_Business_NotLitigationInfo));

        if (!string.IsNullOrEmpty(entNotLitigation.HouseAddress))
        {
            entNotLitigation = CompleteNotLitigation(entNotLitigation, "非诉更新");
            //非诉信息录入
            bllNotLitigation.Update(entNotLitigation);
            string text = string.Empty;
            text = CurrentUserInfo.UserName + "：非诉更新。成交编号：" + entNotLitigation.ContractCode;
            AddLog(text, BusinessType.BusinessTypeComboList()["OprType_UpdateNotLitigation"].ToString());
        }

        return retExecResult(Constants.ExecResult.Succ, Resources.Message.Msg_UpNotLitigation_Succ, "");
    }

    /// <summary>
    /// 上传附件
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string FileUpload(HttpContext context)
    {
        try
        {
            string recordId = context.Request.Params["recordId"];
            HttpPostedFile file = context.Request.Files["FileData"];
            string strFileName = file.FileName.ToString();
            string strFileExt = strFileName.Substring(strFileName.LastIndexOf('.'));

            bool inExt = false;
            for (int i = 0; i < FileExt.Length; i++)
            {
                if (strFileExt.Equals(FileExt[i].ToString()))
                {
                    inExt = true;
                }
            }

            if (!inExt)
            {
                return retExecResult(Constants.ExecResult.Error, "" + strFileExt + "文件格式不允许上传！", "");
            }
            else
            {
                Upload(context, Constants.FilePath_Litigation, recordId);
                return retExecResult(Constants.ExecResult.Succ, Resources.Message.Msg_LitigationUpLoad_Succ, "");
            }
        }
        catch (Exception ex)
        {
            return retExecResult(Constants.ExecResult.Error, ex.Message, "");
        }
    }

    /// <summary>
    /// 附件列表
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string ShowList(HttpContext context)
    {
        //返回数据
        string strRet = string.Empty;
        
        try
        {
            string RelationId = context.Request.Params["RelationId"];
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat(" RelationId='{0}' ",RelationId);
            
            //合同附件业务类
            Chenxin.Lib.Business.BLL.ContractAttachment bllAtt = new Chenxin.Lib.Business.BLL.ContractAttachment();
            string strWhere = sb.ToString();
            System.Data.DataSet ds = bllAtt.GetList(strWhere);
            //Constants.Pagination cp = GetJson(ds);
            //strRet = string.Format("{{success:1,msg:'',data:{{count:{0},html:'{1}'}}}}", cp.count, cp.data);
            //return strRet;
            
            return strRet = string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", ds.Tables[0].Rows.Count, JsonHelp.Convert2Json(ds.Tables[0]));
        }
        catch (Exception ex)
        {
            strRet = retExecResult(Constants.ExecResult.Error, ex.Message, "");
            return strRet;
        }
    }
    
    /// <summary>
    /// 保存文件
    /// </summary>
    /// <param name="context">请求上下文</param>
    public void Upload(HttpContext context, string strFile, string recordId)
    {
        try
        {
            Random rd = new Random();
            HttpPostedFile file = context.Request.Files["FileData"];

            string savePath = context.Server.MapPath(Constants.DIRECTORY + strFile);
            string fileName = file.FileName.ToString();
            string saveName = DateTime.Now.ToString("yyyyMMddhhmmss") + rd.Next(100, 999).ToString() + fileName.Substring(fileName.LastIndexOf('.'));

            if (file != null)
            {
                if (!System.IO.Directory.Exists(savePath))
                {
                    System.IO.Directory.CreateDirectory(savePath);
                }
                file.SaveAs(savePath + saveName);

                ContractAttachment bllContract = new ContractAttachment();

                Chenxin.Lib.Business.Entity.ContractAttachment entAtt = new Chenxin.Lib.Business.Entity.ContractAttachment();

                entAtt.RecordId = Guid.NewGuid();
                entAtt.RelationId = new Guid(recordId);
                entAtt.FileName = fileName;
                entAtt.Remark = "上传非诉相关附件";
                entAtt.AttType = 30;
                entAtt.AddTime = DateTime.Now;
                entAtt.CityId = CurrentUserInfo.CityId;
                entAtt.CityName = CurrentUserInfo.CityName;
                entAtt.CompanyId = CurrentUserInfo.CompanyId;
                entAtt.CompanyName = CurrentUserInfo.CompanyName;
                entAtt.DepartId = CurrentUserInfo.DepartId;
                entAtt.DepartName = CurrentUserInfo.DepartName;
                entAtt.UserId = CurrentUserInfo.UserId;
                entAtt.UserName = CurrentUserInfo.UserName;

                if (!string.IsNullOrEmpty(savePath))
                {
                    entAtt.Path = strFile + saveName;
                }

                bllContract.Add(entAtt);

                NotLitigationInfo bllNotLit = new NotLitigationInfo();
                Chenxin.Lib.Business.Entity.t_Business_NotLitigationInfo entOldNotLit = new Chenxin.Lib.Business.Entity.t_Business_NotLitigationInfo();
                Chenxin.Lib.Business.Entity.t_Business_NotLitigationInfo entNotLit = new Chenxin.Lib.Business.Entity.t_Business_NotLitigationInfo();
                entOldNotLit = bllNotLit.GetModel(new Guid(recordId));
                entNotLit.HasAttachment = 1;
                entNotLit.HouseAddress = entOldNotLit.HouseAddress;
                entNotLit.AcceptedDate = entOldNotLit.AcceptedDate;
                entNotLit.MailDate = entOldNotLit.MailDate;
                entNotLit.Description = entOldNotLit.Description;
                entNotLit.Memo = entOldNotLit.Memo;
                entNotLit.RecordId = entOldNotLit.RecordId;
                entNotLit.ContractId = entOldNotLit.ContractId;
                entNotLit.ContractCode = entOldNotLit.ContractCode;
                entNotLit.AppCityId = entOldNotLit.AppCityId;
                entNotLit.AppCity = entOldNotLit.AppCity;
                entNotLit.AppCompanyId = entOldNotLit.AppCompanyId;
                entNotLit.AppCompany = entOldNotLit.AppCompany;
                entNotLit.AppDepartId = entOldNotLit.AppDepartId;
                entNotLit.AppDepart = entOldNotLit.AppDepart;
                entNotLit.AddPersonId = entOldNotLit.AddPersonId;
                entNotLit.AddPerson = entOldNotLit.AddPerson;
                entNotLit.AddTime = entOldNotLit.AddTime;

                bllNotLit.Update(entNotLit);
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }
    
    //*******************************************
    //功能概要       ：填充诉讼信息字段
    //参数説明       ：context 请求上下文
    //返回值説明     ：诉讼信息实体
    //功能詳細       ：填充诉讼信息字段
    //作成者         ：zou.xiaochun
    //作成日         ：2010-09-28
    //*******************************************
    private Chenxin.Lib.Business.Entity.t_Business_NotLitigationInfo CompleteNotLitigation(Chenxin.Lib.Business.Entity.t_Business_NotLitigationInfo entNoLitigation, string status)
    {
        try
        {
            //诉讼信息处理业务类
            Chenxin.Lib.Business.BLL.NotLitigationInfo bllNoLitigation = new Chenxin.Lib.Business.BLL.NotLitigationInfo();
            Chenxin.Lib.Business.Entity.t_Business_NotLitigationInfo entOldNoLitigation = bllNoLitigation.GetModel(entNoLitigation.RecordId);

            if (status.Equals("非诉申请"))
            {
                entNoLitigation.RecordId = Guid.NewGuid();
                entNoLitigation.AppCityId = CurrentUserInfo.CityId;
                entNoLitigation.AppCity = CurrentUserInfo.CityName;
                entNoLitigation.AppCompanyId = CurrentUserInfo.CompanyId;
                entNoLitigation.AppCompany = CurrentUserInfo.CompanyName;
                entNoLitigation.AddTime = DateTime.Now;
                entNoLitigation.AddPersonId = CurrentUserInfo.UserId;
                entNoLitigation.AddPerson = CurrentUserInfo.UserName;
            }
            else if (status.Equals("非诉更新"))
            {
                entNoLitigation.RecordId = entOldNoLitigation.RecordId;
                entNoLitigation.ContractId = entOldNoLitigation.ContractId;
                entNoLitigation.ContractCode = entOldNoLitigation.ContractCode;
                entNoLitigation.AppCityId = CurrentUserInfo.CityId;
                entNoLitigation.AppCity = CurrentUserInfo.CityName;
                entNoLitigation.AppCompanyId = CurrentUserInfo.CompanyId;
                entNoLitigation.AppCompany = CurrentUserInfo.CompanyName;
                entNoLitigation.AddTime = DateTime.Now;
                entNoLitigation.AddPersonId = CurrentUserInfo.UserId;
                entNoLitigation.AddPerson = CurrentUserInfo.UserName;
            }
            return entNoLitigation;
        }
        catch (Exception ex)
        {
            return null;
        }
    }
}